package com.itgacl.magic4j.common.handler;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.itgacl.magic4j.common.bean.LoginUser;
import com.itgacl.magic4j.common.context.LoginUserContext;
import com.itgacl.magic4j.libcommon.constant.Constants;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 * 自动填充公共字段
 */
@Slf4j
@Component
public class FillMetaObjectHandler implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        Object createUser = getFieldValByName("createUser", metaObject);
        Object updateUser = getFieldValByName("updateUser", metaObject);
        Object createTime = getFieldValByName("createTime", metaObject);
        Object updateTime = getFieldValByName("updateTime", metaObject);
        LoginUser loginUser = LoginUserContext.get();
        if(createUser==null){
            if(loginUser!=null){
                this.setFieldValByName("createUser", loginUser.getId(), metaObject);
            }
        }
        if(updateUser==null){
            if(loginUser!=null){
                this.setFieldValByName("updateUser", loginUser.getId(), metaObject);
            }
        }
        if (createTime == null) {
            this.setFieldValByName("createTime", LocalDateTime.now(), metaObject);
        }
        if (updateTime == null) {
            this.setFieldValByName("updateTime", LocalDateTime.now(), metaObject);
        }
        this.setFieldValByName("deleteFlag", Constants.DELETE_FLAG.NO, metaObject);
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        Object updateUser = getFieldValByName("updateUser", metaObject);
        Object updateTime = getFieldValByName("updateTime", metaObject);
        LoginUser loginUser = LoginUserContext.get();
        if(updateUser==null){
            if(loginUser!=null){
                this.setFieldValByName("updateUser", loginUser.getId(), metaObject);
            }
        }
        if (updateTime == null) {
            //填充updateTime属性的值
            this.setFieldValByName("updateTime", LocalDateTime.now(), metaObject);
        }
    }
}